<template>
  <base-modal class="setting-modal" :title="$t('order.setting.houseDialog.text1')" :show.sync="dialogVisible" width="70%" @close="closeDialog">
        <div class="add-parts-dialog-container">
            <div class="add-parts-dialog-header">
                <el-input
                    class="add-parts-dialog-search-btn"
                    v-model="pageInfo.keyword"
                    :placeholder="$t('order.setting.houseDialog.text2')"
                >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-select v-model="pageInfo.type" :placeholder="$t('order.setting.houseDialog.text3')">
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-button class="primary_btn" type="primary" slot="append" @click="handleSearch">{{ $t('common.base.search') }}</el-button>
                <el-button @click="handleInit">{{ $t('common.base.reset')}}</el-button>
            </div>

            <div class="add-parts-dialog-main">
                <div class="add-parts-dialog-left">
                  <div class="add-parts-dialog-left-title">
                      <div>
                      <h3>{{ $t('order.setting.houseDialog.text4') }}</h3>
                      </div>
                      <span>{{ `${selectedLists.length} / ${total}` }}</span>
                  </div>

                  <template v-if="tableData.length">
                      <el-table
                        ref="wareHouseTable"
                        :data="tableData"
                        stripe
                        border
                        row-key="id"
                        style="width: 100%"
                        @select="handleSelect"
                        @select-all="handleSelectAll"
                      >
                      <el-table-column
                          type="selection"
                          :reserve-selection="true"
                          width="40"
                      >
                      </el-table-column>
                      <el-table-column prop="warehouseNo" :label="$t('order.setting.houseDialog.c1')" width="200" v-if="warehouseNo">
                      </el-table-column>
                      <el-table-column prop="name" :label="$t('order.setting.houseDialog.c2')">
                      </el-table-column>
                      <el-table-column prop="type" :label="$t('order.setting.houseDialog.c3')" width="88">
                      </el-table-column>
                      </el-table>
                      <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="total"
                        :page-size="pageInfo.pageSize"
                        :current-page="pageInfo.pageNum"
                        @current-change="handlePageChange"
                        >
                      </el-pagination>
                  </template>
                </div>

                <div class="add-parts-dialog-right">
                    <div class="add-parts-dialog-right-title">{{ $t('order.setting.houseDialog.text5') }}</div>
                    <div class="add-parts-dialog-right-content">
                        <draggable
                            v-model="selectedLists"
                            v-bind="{
                            animation: 500,
                            }"
                            draggable=".list_div"
                            @end="handleEnd"
                          >
                            <transition-group>
                              <div
                                v-for="(item, index) in selectedLists"
                                :key="'selected'+item.id"
                                class="list_div"
                                >
                                  <div class="nested-draggable-name">
                                      <span class="nested-draggable-name-label">
                                          <i class="iconfont icon-tuozhuaipaixu"></i>
                                      </span>
                                      <span class="nested-draggable-name-text">{{ index + 1 }} - {{ item.name }}</span>
                                  </div>
                                  <div class="nested-draggable-name-label-actions">
                                      <span class="nested-draggable-name-label nested-draggable-name-fixed" @click="istop(index, item.id)">
                                          <i class="iconfont icon-pushpin"></i>
                                      </span>
                                      <span class="nested-draggable-name-label nested-draggable-name-delete" @click="reduce(index)">
                                          <i class="iconfont icon-close-circle"></i>
                                      </span>
                                  </div>
                              </div>
                            </transition-group>
                        </draggable>
                    </div>
                </div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">{{ $t('common.base.close')}}</el-button>
            <el-button type="primary" :disabled="!selectedLists.length" @click="handleSave">{{ $t('common.base.save')}}</el-button>
        </div>
    </base-modal>
</template>

<script>
import draggable from 'vuedraggable';
import _ from 'lodash';
import { getSparepartOrMaterialWarehouse, searchWarehouseType } from '@src/api/LinkcApi';
import { getRootWindow } from '@src/util/dom'

export default {
  name: 'setting-store-house-dialog',
  components: {
    draggable,
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dialogVisible: false,
      pending: false,
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        type: ''
      },
      options: [{
        id: '备件库',
        name: '备件库'
      }, {
        id: '不良品库',
        name: '不良品库'
      }, {
        id: '区域库',
        name: '区域库'
      }, {
        id: '备件其他库',
        name: '备件其他库'
      }],
      total: 0,
      selectedLists: [],
      tableData: [],
      warehouseNo: true
    };
  },
  computed: {
    // 仓库是否是3.0
    isCloudWarehouse() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.cloudwarehouse || false
    },
  },
  methods: {
    async openDialog() {
      this.dialogVisible = true;
      if (this.isCloudWarehouse) {
        this.getWarehouseType()
      }

      this.selectedLists = _.cloneDeep(this.value);
      this.warehouseNo = true;
      this.handleSearch();
    },
    // 关闭
    closeDialog() {
        this.dialogVisible = false;
        this.pageInfo = this.$options.data().pageInfo;
    },
    // 3.0获取仓库类型
    getWarehouseType() {
      searchWarehouseType().then(res => {
        if (res.success) {
          this.options = res.data || []
        }
      })
    },
    async getList() {
      try{
          const result = await getSparepartOrMaterialWarehouse(this.pageInfo)
          if (!result.success) return;
          const { list, total } = result.data;
          this.total = total;

          this.tableData = list.map(item => {
            const {
              id,
              warehouseNo,
              name,
              type,
            } = item;
            if (!warehouseNo && this.warehouseNo) {
              this.warehouseNo = false
            }
            return {
              id,
              warehouseNo,
              name,
              type,
            };
          });
          
      } catch(err){
          console.warn(err)
      } finally {
      }
    },
    handleEnd() {},
    renderPartsSelection(value = []) {
      this.$nextTick(() => {
        // 清空操作
        this.$refs.wareHouseTable.clearSelection();

        if (value.length === 0) return;
        value.forEach(row => {
            const item = this.tableData.find(v => v.id === row.id)
            if (item) this.$refs.wareHouseTable.toggleRowSelection(item);
        });
        this.selectedLists = value;
      });
    },
    // 搜索
    async handleSearch() {
      await this.getList();

      // 重新渲染多选框状态
      this.renderPartsSelection(this.selectedLists);
    },
    // 重置
    handleInit() {
      this.pageInfo = {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
        type: ''
      };

      this.handlePageChange(1);
    },
    // 置顶
    istop(index, id) {
        let item = this.selectedLists.filter(l => { return l.id === id})
        this.selectedLists.splice(index, 1)
        this.selectedLists.unshift(item[0])
    },
    // 移除
    reduce(index) {
      const tableIndex = this.tableData.findIndex(
        item => item.id === this.selectedLists[index].id
      );

      this.selectedLists.splice(index, 1);
      if (tableIndex > -1) {
        this.$nextTick(() => {
          this.$refs.wareHouseTable.toggleRowSelection(
            this.tableData[tableIndex]
          );
        });
      }
    },
    handleSelect(_, row) {
      const index = this.selectedLists.findIndex(f => f.id === row.id);
      if (index === -1) return this.selectedLists.push(row);

      this.selectedLists.splice(index, 1);
    },
    handleSelectAll(selection) {
       this.tableData.forEach(v => {
          const index = this.selectedLists.findIndex(f => f.id === v.id);
          if (selection.length === 0) {
            this.selectedLists.splice(index, 1);
          } else {
            if (index === -1) return this.selectedLists.push(v);
          }
      })
    },
    async handlePageChange(value) {
      this.pageInfo.pageNum = value;
      this.handleSearch();
    },
    // 保存
    handleSave() {
      let list = []
      this.selectedLists.map((item, index) => {
          let obj = {
              warehouseId: item.id,
              sortId: index + 1,
          }
          list.push(obj)
      })
      this.$emit('change', list);
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.add-parts-dialog-container {
  padding: 10px;
  .add-parts-dialog-header {
    display: flex;

    .add-parts-dialog-search-btn {
      width: 260px;
      margin-right: 12px;
    }
    .primary_btn{
      margin-left: 12px;
    }
  }

  .add-parts-dialog-main {
    display: flex;
    min-height: 378px;
    margin-top: 13px;

    .add-parts-dialog-left {
      width: 70%;
      margin-right: 32px;

      .add-parts-dialog-left-title {
        width: 100%;
        height: 32px;
        line-height: 32px;
        display: flex;
        justify-content: space-between;
        background: #f5f5f5;
        border-radius: 4px 4px 0px 0px;
        border: 1px solid #e8e8e8;
        font-family: PingFangSC-Medium, PingFang SC;
        padding: 0 16px;

        h3 {
          font-size: 14px;
          font-weight: 500;
          color: #333333;
          margin: 0 9px 0 0;
          span {
            margin-left: 10px;
          }
        }

        span {
          font-size: 12px;
          font-weight: 400;
          color: #8c8c8c;
        }
      }

      .el-pagination {
        margin-top: 18px;
        float: right;
      }
    }

    .add-parts-dialog-right {
      width: 220px;
      flex: 1;
      border-radius: 4px;
      border: 1px solid #e8e8e8;

      .add-parts-dialog-right-title {
        width: 100%;
        height: 32px;
        line-height: 32px;
        background: #f5f5f5;
        border-radius: 4px 4px 0px 0px;
        padding-left: 16px;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #262626;
      }

      .add-parts-dialog-right-content {
        width: 100%;
        // height: calc(100% - 32px);
        height: 500px;
        overflow-x: hidden;
        overflow-y: scroll;
        padding: 10px;
        display: flex;
        flex-direction: column;

        .list_div{
            height: 30px;
            line-height: 30px;
            cursor: move;
            display: flex;
            justify-content: space-between;
            align-items: center;
            &:hover{
                background: #E7F7F6;
                .nested-draggable-name-label i{
                    display: block;
                }
            }
        }
      }
    }
  }
}

.add-parts-dialog ::v-deep .el-dialog__body {
  padding: 18px;
}
::v-deep .el-input-group__append,
.el-input-group__prepend {
  border-radius: 0 4px 4px 0;
}
.add-parts-dialog-left ::v-deep .el-table {
  border-left: 1px solid #ebeef5;
}
</style>
